﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;

namespace NetfractionHub.LocalMachine.BotCommands.Handler
{
    [CommandHandler("help")]
    public class Help : CommandHandler
    {
        public override BotReturnStatus HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
        {
            if (message.UnnamedArguments.Count == 1)
            {
                if (this.ParentBot.BotCommands.ContainsKey(message.UnnamedArguments[0]))
                {
                    object[] attrs = this.ParentBot.BotCommands[message.UnnamedArguments[0]].GetType().GetCustomAttributes(typeof(CommandHandlerAttribute), false);
                    if (attrs.Length > 0)
                    {
                        if (string.IsNullOrEmpty((attrs[0] as CommandHandlerAttribute).Description))
                            return new BotReturnStatus(false, string.Format("No help string found for command: {0}", message.UnnamedArguments[0]));

                        string messageToSend = (attrs[0] as CommandHandlerAttribute).Description;
                        messageToSend = messageToSend.Replace("<trigger>", BotNode.GetCommandPrefixes(this.ParentBot)[0] + message.UnnamedArguments[0]);
                        this.ParentBot.SendEchoMessageFromBot(source, messageToSend);
                    }
                    else
                        return new BotReturnStatus(false, string.Format("No help string found for command: {0}", message.UnnamedArguments[0]));
                }
            }
            else if (message.ArgumentsCount == 0)
            {
                StringBuilder messageToSend = new StringBuilder();
                foreach (string key in this.ParentBot.DistinctCommandKeys)
                {
                    foreach (CommandHandlerAttribute attrib in this.ParentBot.BotCommands[key].GetType().GetCustomAttributes(typeof(CommandHandlerAttribute), false)
                        .Where(p => p is CommandHandlerAttribute))
                    {
                        if (string.IsNullOrEmpty(attrib.Description))
                            messageToSend.AppendLine(string.Format("No help string found for command: {0}", key));
                        else
                            messageToSend.AppendLine(attrib.Description.Replace("<trigger>", BotNode.GetCommandPrefixes(this.ParentBot)[0] + key));
                    }
                }

                if (messageToSend.Length > 0)
                    return new BotReturnStatus(true, messageToSend.ToString());
            }

            return false;
        }
    }
}
